package com.atguigu.msmservice.Controller;


import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/msmservice/msm")
@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    //springboot封装的redis对象
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信验证码
    @GetMapping("send/{phone}")
    public R sengMsm(@PathVariable("phone") String phone){
        //从redis获取验证码，如果为空就生成
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.ok().message("验证码已经发送");
        }

        //手机号，生成验证码传入阿里服务
        //1、生成验证码
         code = RandomUtil.getFourBitRandom();
        //存储数据
        Map<String,Object> map = new HashMap<>();
        map.put("code",code);
        //service中处理短信发送
        //为了方便code使用json传送
        boolean isSend = msmService.send(map,phone);
        if(isSend) {
            //把验证码放入redis，设置有限时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok().message("发送成功");
        } else {
            return R.error().message("短信发送失败");
        }
    }

}
